

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/10/25 19:48
 * hashCode 和 equals的理解
 */


class Person{
    public String ID;

    public Person(String ID){
        this.ID = ID;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(ID, person.ID);
    }

    @Override
    public int hashCode() {
        return Objects.hash(ID);
    }

    @Override
    public String toString() {
        return "Person{" +
                "ID='" + ID + '\'' +
                '}';
    }
}

/**
 * hashCode就是对象在哈希表中确定对象位置的，equals比较两相等性
 */
public class HashBuck2 <K,V>{
    static class Node<K,V>{
        public K key;
        public V value;
        public Node<K,V> next;

        public Node(K key,V value){
            this.key = key;
            this.value = value;
        }
    }

    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int size;

    public void put(K key,V value){
        int hash = key.hashCode();//获取key位置
        int index = hash % array.length;

        for (Node<K,V> cur = array[index]; cur != null; cur = cur.next){
            if(cur.key.equals(key)){
                cur.value = value;
                return ;
            }
        }
        //如果没有找到就插入新节点
        Node<K,V> node = new  Node(key, value);
        //头插
        node.next = array[index];
        array[index] = node;
        size++;
   }

    public V get(K key){
        int hash = key.hashCode();
        int index = hash % array.length;

        Node<K,V> head = array[index];
        for(Node<K,V> cur = head; cur != null; cur = cur.next){
            if(cur.key.equals(key)){
                return cur.value;
            }
        }
        return null;
    }



    public static void main(String[] args) {
        Person person1 = new Person("522");
        Person person2 = new Person("522");
        HashBuck2<Person,String> hashBuck2 = new HashBuck2<>();
        hashBuck2.put(person1,"xie");
        System.out.println(hashBuck2.get(person2));
    }



    public static void main1(String[] args) {
        Person person1 = new Person("522");
        Person person2 = new Person("522");
        System.out.println(person1.hashCode());
        System.out.println(person1.hashCode());
    }
}
